/*
* 苏州海管家物流科技有限公司（https://www.hgj.com/）.
* 苏公网安备32059002003385号 © 2015-2022 Hgj.com All Rights Reserved. | 苏ICP备15030950号.
* @Date: 2022.05.22.
* @Author
* @Description 企点管理后台 - 数据加载 axios 封装.
**/
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { HTTP_METHOD } from "@/utils/type"

/* interface ICancelObj {
       url: string,
       data?: unknown,
       method: HTTP_METHOD,
   } */
interface IParams {
    url: string,
    method: HTTP_METHOD,
    data?: unknown,
    params?: unknown,
}

let loginFlag = false

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

// create
console.log('process.env.VUE_APP_HOST-----------------', process.env.VUE_APP_HOST, process)
const request = axios.create({
    baseURL: process.env.VUE_APP_HOST,
    // timeout: 15 * 1000, // 请求超时时间
    headers: {
        appName: 'whale_common_pc'
    },
    withCredentials: false, // true：服务端设置Access-Control-Allow-Origin不能为 " * ", 必须是源地址
    transformRequest: [ // 请求前的数据处理
        (data = {}, headers) => {
            console.log('data--headers-----------', data, headers)
            return JSON.stringify(data)
        }
        // ...axios.defaults.transformRequest
    ],
    /*
        // 请求数组 参数序列化
        qs.stringify({ids: [1, 2, 3]}, {indices: false})
        // 形式：ids=1&ids=2&id=3

        qs.stringify({ids: [1, 2, 3]}, {arrayFormat: 'indices'})
        // 形式：ids[0]=1&ids[1]=2&ids[2]=3

        qs.stringify({ids: [1, 2, 3]}, {arrayFormat: 'brackets'})
        // 形式：ids[]=1&ids[]=2&ids[]=3

        qs.stringify({ids: [1, 2, 3]}, {arrayFormat: 'repeat'})
        // 形式： ids=1&ids=2&id=3
   */
    paramsSerializer: (params) => {
        console.log('params----------------', params)
        return JSON.stringify(params)
    }
})
/**
 *@Description 接口请求前监听 - 请求发送.
 *@Return .
**/
request.interceptors.request.use((config) => {
    return config
}, (err) => {
    return Promise.reject(err)
})
/**
 *@Description 接口返回监听 - 请求响应.
 *@Return .
**/
request.interceptors.response.use(async (response) => {
    // console.log('axios response 数据结果返回*****', response)
    const { code, message } = response.data
    if ( code === 1006 || code === 401 || message === '未登录' || message === '获取用户信息失败') {
        if (!loginFlag && !window.location.host.includes('localhost')) {
            loginFlag = true
            console.log('进入之后 在调式=============================')

            /* const result = await ElMessage.confirm( '当前未登录，是否去登录?', '提示')
               if (result) {
                   window.location.href = process.env.VUE_APP_MANAGE_URL
               } */

        }
    } else if (code === 403) {
        ElMessage.warning('此用户没有权限，请重新登录！')
    } else if (code === 500) {
        ElMessage.error(message)
    }

    return response.data

}, (error) => {
    /* console.log('axios error 数据结果返回*****', error)
       let { code, message } = error.response.data */
    if (!error?.response) {
        return false
    }

    let errMsg = '系统繁忙'
    if (error?.response?.data?.message) {
        errMsg = error?.response?.data?.message
    }

    ElMessage.error(errMsg)
    return Promise.reject(error)
})
/**
 *@Description 同时只会有一个请求，如果请求多次，会自动取消上一次的 request.
 *@Return .
**/
const useSingleRequest = (request: any) => {

    // const cancelObj: ICancelObj = { data: undefined, method: HTTP_METHOD.POST, url: ""}

    if (!request?.defaults) {
        throw new Error('request is not a axios object')
    }

    return (config: IParams) => {

        console.log('request config=======================', config)

        const key = `${config.url}${config.method}`

        console.log('key-----------', key)

        /* if (cancelObj[key]) {
               cancelObj[key]()
           } */

        const params = {
            cancelToken: new axios.CancelToken((c) => {
                // console.log('cancelObj--------', cancelObj)
                console.log('c--------', c)
                // cancelObj[key] = c
            }),
            ...config
        }

        return request(params)
    }
}

// 同时只会有一个请求，如果请求多次，会自动取消上一次的request
export const singleRequest = useSingleRequest(request)

export default request
